import CustomUpload from '@/components/CustomUpload';
import { PlusOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import ProForm, { ProFormCheckbox, ProFormDigit, ProFormRadio, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import { message, Menu, Row, Col, Result } from 'antd';
import type { RadioGroupProps } from 'antd';
import React, { useRef, useState } from 'react';
import { useIntl } from 'umi';
import type {
    ProFormInstance,
} from '@ant-design/pro-form';
import {
    getApiSiteSettingBase as GetSettings,
    putApiSiteSettingByIdBase as UpdateSettings,
} from '@/services/furion-cms/siteSetting';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

const { Item: MenuItem } = Menu;

const SiteSettings: React.FC = () => {
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    const AccessMenuItem = useCustomAccess(MenuItem);
    const [uploadDisplay, setUploadDisplay] = useState(true);
    const [errorMessage, setErrorMessage] = useState<string>();
    const [storageMode, setStorageMode] = useState<number>();
    const [storageModeOptions, setStorageModeOptions] = useState<RadioGroupProps['options']>([]);
    const [activeKey, setActiveKey] = useState<string>('base');

    const formRef = useRef<ProFormInstance<API.SiteSettingsDto>>();

    const getCardTitle = (key: string) => {
        switch (key) {
            case 'safe': return intl.formatMessage({ id: 'pages.settings.safety', defaultMessage: '安全设置' });
            case 'other': return intl.formatMessage({ id: 'pages.settings.other', defaultMessage: '其他' });
            default: return intl.formatMessage({ id: 'pages.settings.site', defaultMessage: '基本信息' });
        }
    }

    const uploadButton = (
        uploadDisplay && <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>
                {intl.formatMessage({
                    id: 'pages.settings.site.upload',
                    defaultMessage: '选择上传'
                })}
            </div>
        </div>
    );

    const limitDecimals = (value: any) => {
        return value.replace(/^(0+)|[^\d]+/g, '');
    };

    const defaultDigitFieldProps = {
        formatter: limitDecimals,
        parser: limitDecimals,
    }

    return (errorMessage ? <Result status="500"
        title="访问出错"
        subTitle={errorMessage} /> : <PageContainer
            breadcrumbRender={false}>
        <ProCard split="vertical">
            <ProCard colSpan="224px" bodyStyle={{
                padding: '18px 0'
            }}>
                <Menu mode="inline"
                    defaultSelectedKeys={['base']}
                    onClick={({ key }) => setActiveKey(key)}
                >
                    <AccessMenuItem code={PermissionsDefinition.SiteSettings.BasicInfoSettings}
                        key="base">
                        {intl.formatMessage({
                            id: 'pages.settings.site',
                            defaultMessage: '基本设置'
                        })}
                    </AccessMenuItem>
                    <AccessMenuItem code={PermissionsDefinition.SiteSettings.SafeSettings}
                        key="safe">
                        {intl.formatMessage({
                            id: 'pages.settings.safety',
                            defaultMessage: '安全设置'
                        })}
                    </AccessMenuItem>
                    <AccessMenuItem code={PermissionsDefinition.SiteSettings.OtherSettings}
                        key="other">
                        {intl.formatMessage({
                            id: 'pages.settings.other',
                            defaultMessage: '其他'
                        })}
                    </AccessMenuItem>
                </Menu>
            </ProCard>
            <ProCard title={<span style={{
                fontSize: 20
            }}>{getCardTitle(activeKey)}</span>}>
                <ProForm<API.SiteSettingsDto>
                    formRef={formRef}
                    // initialValues={data}
                    submitter={{
                        render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
                    }}
                    onFinish={async (values) => {
                        try {
                            await UpdateSettings({ id: values.id! }, values);
                            message.success(intl.formatMessage({
                                id: 'pages.settings.success',
                                defaultMessage: '配置保存成功'
                            }));
                        } catch { }
                        console.log('SiteSettings-Finish', values);
                    }}
                    request={() => {
                        return GetSettings({ skipErrorHandler: true })
                            .then(({ data }) => {
                                if (data?.logo) setUploadDisplay(false);
                                setStorageMode(data?.objectStorageMode);
                                setStorageModeOptions(data?.storageModeList?.map(m => ({ value: m[0], label: m[1] })));
                                return {
                                    ...data
                                };
                            }).catch(({ data }) => {
                                setErrorMessage(data?.errorMessage)
                                return Promise.reject(data?.errorMessage);
                            });
                    }}
                >
                    <ProFormText name="id" hidden />
                    {/* 基础配置 */}
                    <Row gutter={24} style={activeKey === 'base' ? {} : { display: 'none' }}>
                        <Col span={10}>
                            <ProFormText name="name"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.name',
                                    defaultMessage: '网站名称'
                                })}
                                placeholder={intl.formatMessage({
                                    id: 'pages.settings.site.name.placeholder',
                                    defaultMessage: '请输入网站名称'
                                })}
                                rules={[{
                                    required: true,
                                    message: intl.formatMessage({
                                        id: 'pages.settings.site.name.rules',
                                        defaultMessage: '网站名称是必填项'
                                    })
                                }]}
                            />
                            <ProFormText name="title"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.title',
                                    defaultMessage: '网站标题'
                                })}
                                placeholder={intl.formatMessage({
                                    id: 'pages.settings.site.title.placeholder',
                                    defaultMessage: '请输入网站标题'
                                })}
                                rules={[{
                                    required: true,
                                    message: intl.formatMessage({
                                        id: 'pages.settings.site.title.rules',
                                        defaultMessage: '网站标题是必填项'
                                    })
                                }]}
                            />
                            <ProFormText name="hostUrl"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.hosturl',
                                    defaultMessage: '网站网址'
                                })}
                                placeholder={intl.formatMessage({
                                    id: 'pages.settings.site.hosturl.placeholder',
                                    defaultMessage: '请输入网址的访问地址'
                                })}
                            />
                            <ProFormTextArea name="keywords"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.keywords',
                                    defaultMessage: '网站关键词'
                                })}
                                tooltip={intl.formatMessage({
                                    id: 'pages.settings.site.keywords.tip',
                                    defaultMessage: '网站关键词标签,通常用于搜索引擎在爬取网页时识别'
                                })}
                            />
                            <ProFormTextArea name="description"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.description',
                                    defaultMessage: '网站描述'
                                })}
                                tooltip={intl.formatMessage({
                                    id: 'pages.settings.site.description.tip',
                                    defaultMessage: '网站描述标签,通常用于搜索引擎在爬取网页时识别'
                                })}
                            />
                            <ProFormTextArea name="copyright"
                                label={intl.formatMessage({
                                    id: 'pages.settings.site.copyright',
                                    defaultMessage: '网站版权信息'
                                })}
                            />
                        </Col>
                        <Col span={14}>
                            <ProForm.Item name="logo" label={intl.formatMessage({
                                id: 'pages.settings.site.logo',
                                defaultMessage: '网站LOGO'
                            })}
                                valuePropName="fileValue">
                                <CustomUpload dir="site/"
                                    uploadProps={{
                                        listType: 'picture-card',
                                        onRemove: () => {
                                            formRef.current?.setFieldsValue({ logo: '' });
                                            setUploadDisplay(true);
                                        },
                                        onChange: (e) => {
                                            if (e.file.status === 'uploading') setUploadDisplay(false);
                                            console.log('site - CustomUpload', e);
                                        },
                                        onPreview: async (file) => {
                                            let src = file.url;
                                            if (!src) {
                                                src = await new Promise(resolve => {
                                                    const reader = new FileReader();
                                                    reader.readAsDataURL(file.originFileObj!);
                                                    reader.onload = () => resolve(reader.result as string);
                                                });
                                            }
                                            const image = new Image();
                                            image.src = src!;
                                            const imgWindow = window.open(src);
                                            imgWindow?.document.write(image.outerHTML);
                                        }
                                    }}
                                    onFinish={results => {
                                        if (results.length) {
                                            const uplodaResult = results[0];
                                            if (uplodaResult.success) {
                                                formRef.current?.setFieldsValue({
                                                    logo: uplodaResult?.fileUri
                                                });
                                            }
                                            else {
                                                message.error(uplodaResult.error);
                                            }
                                        }
                                    }}
                                    crop ren>
                                    {uploadButton}
                                </CustomUpload>
                            </ProForm.Item>
                        </Col>
                    </Row>
                    {/* 安全设置 */}
                    <div style={activeKey === 'safe' ? {} : { display: 'none' }}>
                        <h3>
                            {intl.formatMessage({
                                id: 'pages.settings.safe.lock',
                                defaultMessage: '锁定设置'
                            })}
                        </h3>
                        <ProFormCheckbox name="isSafeLock" extra={intl.formatMessage({
                            id: 'pages.settings.safe.lock.enable.extra',
                            defaultMessage: '对未能验证通过的登录请求进行暂时性的锁定.'
                        })}>{intl.formatMessage({
                            id: 'pages.settings.safe.lock.enable',
                            defaultMessage: '启用锁定'
                        })}</ProFormCheckbox>
                        <ProFormDigit name="safeLockDuration"
                            label={intl.formatMessage({
                                id: 'pages.settings.safe.lock.time',
                                defaultMessage: '锁定时间(秒)'
                            })}
                            width="lg"
                            fieldProps={{
                                ...defaultDigitFieldProps
                            }}
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.lock.time.extra',
                                defaultMessage: '当锁定发生时用户被的锁定的时间(秒).'
                            })} />
                        <ProFormDigit name="safeVerifyMaxFialNumber"
                            label={intl.formatMessage({
                                id: 'pages.settings.safe.lock.failnumber',
                                defaultMessage: '最大失败访问尝试次数'
                            })}
                            width="lg"
                            fieldProps={{
                                ...defaultDigitFieldProps
                            }}
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.lock.failnumber.extra',
                                defaultMessage: '如果启用锁定, 当用户被锁定前失败的访问尝试次数.'
                            })} />
                        <hr />
                        <h3>{intl.formatMessage({
                            id: 'pages.settings.safe.login',
                            defaultMessage: '登录设置'
                        })}</h3>
                        <ProFormCheckbox name="isLoginCaptcha"
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.login.captcha.extra',
                                defaultMessage: '用户尝试登录时启用验证码进行人机验证.'
                            })}>{intl.formatMessage({
                                id: 'pages.settings.safe.login.captcha',
                                defaultMessage: '启用验证码'
                            })}</ProFormCheckbox>
                        <ProFormCheckbox name="isTwoFactorVerify"
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.login.twofactor.extra',
                                defaultMessage: '用户尝试登录时进行双因素身份验证.'
                            })}>{intl.formatMessage({
                                id: 'pages.settings.safe.login.twofactor',
                                defaultMessage: '启用双因素认证'
                            })}</ProFormCheckbox>
                        <ProFormCheckbox name="isPhoneNumberLogin"
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.login.phone.extra',
                                defaultMessage: '可使用账号绑定的手机号进行短信码验证登录.'
                            })}>{intl.formatMessage({
                                id: 'pages.settings.safe.login.phone',
                                defaultMessage: '启用手机号登录'
                            })}</ProFormCheckbox>
                        <ProFormDigit name="captchaDuration"
                            label={intl.formatMessage({
                                id: 'pages.settings.safe.login.captcha.expires',
                                defaultMessage: '验证码有效时间(秒)'
                            })}
                            width="lg"
                            fieldProps={{
                                ...defaultDigitFieldProps
                            }}
                            extra={intl.formatMessage({
                                id: 'pages.settings.safe.login.captcha.expires.extra',
                                defaultMessage: '图形验证码与短信验证码的有效时间(秒).'
                            })} />
                    </div>
                    {/* 其他 */}
                    <div style={activeKey === 'other' ? {} : { display: 'none' }}>
                        <h3>{intl.formatMessage({
                            id: 'pages.settings.other.objectstorage',
                            defaultMessage: '资源库存储方式'
                        })}</h3>
                        <ProFormRadio.Group name="objectStorageMode"
                            options={storageModeOptions}
                            fieldProps={{
                                onChange: (e) => {
                                    formRef.current?.setFieldsValue({
                                        storageHostUrl: '',
                                        storageAccessKey: '',
                                        storageAccessKeySecret: ''
                                    })
                                    setStorageMode(e.target.value);
                                }
                            }}
                        />
                        {storageMode === 0 ? '' : <ProForm.Group title={intl.formatMessage({
                            id: 'pages.settings.other.access',
                            defaultMessage: '接入参数'
                        })} direction="vertical">
                            <ProFormText name="storageHostUrl"
                                label={intl.formatMessage({
                                    id: 'pages.settings.other.access.hosturl',
                                    defaultMessage: 'Bucket地址'
                                })}
                                width="lg"
                                rules={[
                                    {
                                        required: true, message: intl.formatMessage({
                                            id: 'pages.settings.other.access.hosturl.required',
                                            defaultMessage: '请输入Bucket地址'
                                        })
                                    }
                                ]}
                            />
                            <ProFormText name="storageAccessKey"
                                label={storageMode === 1 ? 'Key' : 'SecretId'}
                                width="lg"
                                rules={[
                                    {
                                        required: true
                                    }
                                ]} />
                            <ProFormText name="storageAccessKeySecret"
                                label={storageMode === 1 ? 'Secret' : 'SecretKey'}
                                width="lg"
                                rules={[
                                    {
                                        required: true
                                    }
                                ]} />
                        </ProForm.Group>}
                    </div>
                </ProForm>
            </ProCard>
        </ProCard>
    </PageContainer>)
}

export default SiteSettings;